<template>
  <div class="pagss">
    <div style="height: 20px;"></div>
    <Navvz></Navvz>
    <el-row>


      <el-col :span="24">
        <el-row>
          <el-col :span="24">
            <div class="panel-group2">

              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="数据库配置" name="first">
                  <el-button type="primary" class="mb_20" @click="handleAdd" style="background: #3FC1C9;" :disabled='loading_mysql'>添加</el-button>
                  <el-button style="height:36px;" icon="el-icon-refresh" size="mini" @click="sjksx()">刷新</el-button>
                  <el-table :data="tableData" style="width: 100%" v-loading="loading">
                    <el-table-column type="index" width="50">
                    </el-table-column>

                    <el-table-column prop="nickname" label="用户">
                    </el-table-column>
                    <el-table-column prop="db_name" label="数据库名称">
                    </el-table-column>
                    <el-table-column prop="engine_version" label="引擎版本">
                      <template slot-scope="scope">
                        {{ scope.row.engine_version.title }}
                      </template>
                    </el-table-column>

                    <el-table-column label="进度" header-align="center" align="center">
                      <template slot-scope="scope">
                        <el-button v-if="scope.row.generate_state==1" size="mini" type="warning" :loading="true"></el-button>
                        <el-button v-if="scope.row.generate_state==2" type="success" icon="el-icon-check" circle></el-button>
                        <el-button v-if="scope.row.generate_state==3" type="danger" icon="el-icon-close" circle></el-button>
                      </template>
                    </el-table-column>

                    <el-table-column prop="remark" label="备注"></el-table-column>

                    <!-- <el-table-column prop="created_at" label="时间"></el-table-column> -->

                    <el-table-column label="操作" width="200">
                      <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">更新</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>

                  </el-table>

                  <div class="center ">
                    <pagination v-show="total>0" :total="total" :page.sync="queryParams.noPage" :limit.sync="queryParams.pageSize" @pagination="getList" />
                  </div>
                </el-tab-pane>
                <el-tab-pane label="工具服配置" name="second">

                  <Toolcon></Toolcon>

                </el-tab-pane>
              </el-tabs>

            </div>
          </el-col>
        </el-row>


      </el-col>


    </el-row>


    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body style="margin-top: 300px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" disabled />
        </el-form-item>



        <el-form-item label="引擎版本" prop="teacher_id">
          <el-select v-model="form.engineVersion" placeholder="请选择引擎版本">
            <el-option v-for="item in engineList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="color_b_3FC1C9" :disabled="loading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--    <el-dialog title="提示" :visible.sync="config_value" width="30%" :before-close="handleClose" center :close-on-click-modal="false">
      <span style="font-size: 30px;">申请测试，维护中</span>

    </el-dialog> -->


  </div>
</template>

<script>
  import CountTo from 'vue-count-to'
  import Cookies from 'js-cookie'
  import Vue from 'vue';

  import Navvz from "@/components/Navvz";
  import {
    Notification,
    MessageBox,
    Message,
    Loading
  } from 'element-ui'

  import Sidebartss from "@/components/Sidebartss";
  import * as Database from "@/api/system/database";
  import * as Config from "@/api/system/config";

  import Toolcon from "@/views/center/toolCon";
  import MD5 from 'md5';


  export default {
    name: 'Index',
    components: {
      CountTo,
      Navvz,
      Sidebartss,
      Toolcon,


    },
    data() {
      return {
        cjkfz: null,
        config_value: 1,
        config_remark: null,
        intervalId: null, // 用于存储 setInterval 的返回值，用于后续清除定时器
        activeName: 'first',
        userId: '',
        nickname: '',
        engineList: [], //引擎列表
        // 总条数
        total: 0,
        // 字典表格数据
        tableData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        ulid: '',
        // 查询参数
        queryParams: {
          noPage: 1,
          pageSize: 10
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          dbName: [{
            required: true,
            message: "数据库名称名称不能为空",
            trigger: "blur"
          }],
          engineVersion: [{
            required: true,
            message: '请选择引擎版本',
            trigger: 'change'
          }],
        },
        loading: false,
        loading_mysql: true,


      }
    },
    beforeDestroy() {
      // 在组件销毁前停止定时请求
      this.stopRequest();
    },
    created() {
      this.userId = localStorage.getItem('user_id')
      this.getConfigInofCj(); //获取配置详情---超级开发者
      // this.getConfigInof(); //获取配置详情---控制申请测试菜单
      // this.nickname = localStorage.getItem('username')
      // this.userId = localStorage.getItem('user_id')
      // this.startRequest() //查询PC登录器列表
      // this.getEngineList() //获取引擎列表
    },
    mounted() {

    },
    methods: {

      startRequest() {
        this.getList();
        this.intervalId = setInterval(() => {
          this.getList();
        }, 5000); // 1秒钟请求一次，根据需要调整时间间隔 1000
      },

      stopRequest() {
        clearInterval(this.intervalId); // 清除定时器
      },



      sjksx() {
        this.startRequest();
        this.$message({
          message: '刷新成功',
          type: 'success',
          center: true,
        });
      },

      openFullScreen2() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          loading.close();
        }, 2000);
      },


      //获取引擎列表
      getEngineList() {
        this.loading = true;
        var peres = {}
        peres.type_pj = 1
        Database.engineList(peres).then((response) => {
          this.engineList = response.data.list
          this.loading = false;
        });
      },


      //获取配置详情
      getConfigInof() {
        this.loading = true;
        var peres = {};
        peres.id = 51;
        console.log('aaa', this.userId)
        console.log('bbb', this.cjkfz)
        Config.info(peres).then((response) => {
          if (response.data.config_value == 1 && this.userId != this.cjkfz) {
            this.config_remark = response.data.remark
            this.config_value = response.data.config_value
            this.handleClose();
          } else {
            this.nickname = localStorage.getItem('username')
            this.userId = localStorage.getItem('user_id')
            this.startRequest() //查询PC登录器列表
            this.getEngineList() //获取引擎列表
          }
          this.loading = false;
        });
      },


      //获取配置详情---超级开发者
      getConfigInofCj() {
        this.loading = true;
        var peres = {};
        peres.id = 53;
        Config.info(peres).then((response) => {
          this.cjkfz = response.data.config_value;
          this.getConfigInof();
          this.loading = false;
        });
      },


      handleClose() {
        MessageBox.confirm(this.config_remark, '系统提示', {
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          this.$emit('value-updated', '/center/dataAnalysis');
          this.$router.push({
            path: '/center/dataAnalysis'
          });
        }).catch(() => {
          this.$emit('value-updated', '/center/dataAnalysis');
          this.$router.push({
            path: '/center/dataAnalysis'
          });
        });
      },

      handleClick() {

      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();

        this.ulid = row.ulid
        var peres = {};
        peres.ulid = row.ulid



        peres.type_pj = 1

        Database.Show(peres).then(response => {
          this.form.ulid = response.data.info.ulid;
          this.form.dbName = response.data.info.db_name;
          this.$set(this.form, 'remark', response.data.info.remark)
          this.$set(this.form, 'engineVersion', response.data.info.engine_version.ulid)
          this.open = true;
          this.title = "修改数据库配置";
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        var peres = {};
        peres.dbName = row.db_name
        peres.userId = this.userId
        peres.nickname = this.nickname
        peres.type_pj = 1

        this.$modal.confirm('是否确认删除').then(function() {
          return Database.Delete(peres);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },

      /** 查询数据库配置列表 */
      getList() {

        this.queryParams.userId = this.userId
        this.queryParams.type_pj = 1

        this.loading = true;
        this.loading_mysql = true;
        Database.getList(this.queryParams).then(response => {
          this.tableData = response.data.list;
          if (response.data.isGenerate == 0) {
            this.stopRequest();
          }
          this.total = response.data.pagination.totalCount;
          this.loading = false;
          this.loading_mysql = false;
        }).catch(error => {
          this.stopRequest();
          this.loading = false;
          this.loading_mysql = false;

        });
      },

      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // const loading = this.$loading({
            //   lock: true,
            //   text: '请稍后.....',
            //   spinner: 'el-icon-loading',
            //   background: 'rgba(0, 0, 0, 0.7)'
            // });

            if (this.form.ulid != undefined) {
              this.form.type_pj = 1;
              this.loading = true;
              Database.Update(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.loading = false;

                this.startRequest();
                // this.getList();
              }).catch(error => {
                this.open = false;
                this.loading = false;
                this.startRequest();
              });
            } else {

              this.form.userId = this.userId
              this.form.nickname = this.nickname
              this.form.type_pj = 1

              this.loading = true;
              Database.Add(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.loading = false;
                this.startRequest();

                // this.getList();
              }).catch(error => {
                this.open = false;
                this.loading = false;
                this.startRequest();

              });
            }
          }
        });
      },

      //生成随机字符串
      generateRandomString(length) {
        const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let result = '';
        for (let i = 0; i < length; i++) {
          result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
      },

      /** 新增按钮操作 */
      handleAdd() {
        console.log('aaa', this.tableData)
        if (this.tableData.length >= 10) {
          this.$modal.msgWarning("最多增加10个");
          return
        }
        this.reset();
        this.open = true;
        this.title = "添加数据库配置";
        var str = this.generateRandomString(6);

        if (this.tableData.length > 0) {
          var n1 = this.tableData[0]['db_name'];
          console.log('n1', n1);
          var n2 = n1.slice(8, 13)
          console.log('n2', n2);
          var n3 = Number(n2) + 1;
          console.log('n3', n3);
          var name = 'Toolsdev' + n3 + str;
          console.log('name', name);
        } else {
          var n3 = Number(this.userId) + 1;
          var name = 'Toolsdev' + this.userId + str;
        }
        this.$set(this.form, 'dbName', name);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },

    }
  }
</script>


<style lang="scss" scoped>
  .pagss {
    height: 100%;
    background: #E4EEF9;
  }


  .panel-group1 {
    padding: 25px;
    margin-top: 18px;
    margin-bottom: 0px;
    margin-right: 15px;
    min-height: 220px;
    background: #FFFFFF;
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
  }

  .panel-group2 {
    padding: 25px;
    margin-top: 18px;
    margin-bottom: 0px;
    margin-right: 15px;
    margin-left: 15px;
    min-height: 800px;
    background: #FFFFFF;
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
  }

  // ::v-deep .el-tabs__item.is-active {
  //   color: #fff;
  //   background: #306EF2;
  //   padding-left: 20px;
  // }

  ::v-deep .el-tabs--top .el-tabs__item.is-top:nth-child(2),
  .el-tabs--top .el-tabs__item.is-bottom:nth-child(2),
  .el-tabs--bottom .el-tabs__item.is-top:nth-child(2),
  .el-tabs--bottom .el-tabs__item.is-bottom:nth-child(2) {
    padding-left: 20px;
  }

  ::v-deep .el-tabs--top .el-tabs__item.is-top:last-child,
  .el-tabs--top .el-tabs__item.is-bottom:last-child,
  .el-tabs--bottom .el-tabs__item.is-top:last-child,
  .el-tabs--bottom .el-tabs__item.is-bottom:last-child {
    padding-right: 20px;
  }

  ::v-deep .el-divider--vertical {
    height: 100px;
  }

  ::v-deep .pagination-container .el-pagination {

    position: relative;
  }

  .yhbox {
    padding: 20px;
    width: 320px;
    height: 120px;
    background: #FFFFFF;
    // background: red;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #BBBBBB;
  }

  ::v-deep .el-dialog__header {
    padding: 20px;
    padding-bottom: 0;
  }

  ::v-deep .el-tabs__active-bar {
    background-color: #3FC1C9;
  }

  ::v-deep .el-tabs__item:hover {
    color: #3FC1C9;

  }

  ::v-deep .el-button--primary {
    border-color: #3FC1C9;
  }

  ::v-deep .el-tabs__item.is-active {
    color: #3FC1C9;
  }


  ::v-deep .el-button:hover,
  .el-button:focus {
    color: #000000;
    border-color: #A5EDF1;
    background-color: #A5EDF1;
  }

  .txxbutton {
    ::v-deep .el-button--medium {
      width: 146px;
      height: 52px;
      padding: 10px 20px;
      font-size: 20px;
      border-radius: 4px;
    }
  }
</style>